package com.ch.d0401;

import com.ch.util.DBHelper;
import com.google.gson.Gson;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "NewsServlet", value = "/NewsServlet")
public class NewsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否有缓存的新闻
        Jedis jedis = new Jedis("127.0.0.1",7000);
        // Jedis jedis1 = new Jedis(); 默认 127.0.0.1:6379
        // jedis ~= jdbc 的连接 + 语句对象
        try {
            jedis.get("hyfc_news");
            boolean exists = jedis.exists("hyfc-news");
            Gson gson = new Gson();
            List<Map<String, Object>> maps;
            if(exists){
                //如果有直接返回
                List<String> list = jedis.lrange("hyfc_news", 0, -1);
                maps = new ArrayList<>();
                list.forEach(json->{
                    HashMap hashMap = gson.fromJson(json, HashMap.class);
                    maps.add(hashMap);
                });
            } else {
                // 如果没有则到mysql查询
                String sql = "select * from hyfc_news order by intime desc limit 0,10";
                maps = DBHelper.selectListMap(sql);

                maps.forEach(map->{
                    //保存到redis中（缓存）
                    String json = gson.toJson(map);
                    jedis.rpush("hyfc_news",json);
                });
            }
            String json = gson.toJson(maps);
            response.getWriter().append(json);
        } finally {
            //关闭 jedis
            jedis.close();
        }
        //扩展: 新增新闻要更新缓存数据，删除一个旧的，新增一个新的
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
